<template>
  <div class="app-container">
    <div class="filter-containerEx">
      <el-select v-if="false" v-model="listQuery.lineNumber" :placeholder="$t('equipment.lineNumber')" class="filter-item" @change="handleLineSelect">
        <el-option v-for="item in lineOptions" :key="item.lineNumber" :label="item.lineName" :value="item.lineNumber" />
      </el-select>
      <div v-for="(element,index) in processingList" :key="element.processingId" class="list-complete-item">
        <div class="list-complete-item-handle" @click="handleGetRootList(element)">
          {{ element.processingNumber }}[{{ element.processingId }}]
        </div>
        <div style="float: right ;margin-top: -15px;right:10px; ">
          <span style="margin-right:20px;" @click="handleUpdate(element)">
            <i style="color:blue;" class="el-icon-edit" />
          </span>
          <span @click="handleDelete(element,index)">
            <i style="color:#ff4949" class="el-icon-delete" />
          </span>
        </div>
      </div>
      <el-button class="filter-item" style="vertical-align: center; margin: 10px;" size="mini" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
      <el-button
        v-if="editRight"
        v-waves
        class="filter-item"
        type="warning"
        style="margin-bottom:10px"
        icon="el-icon-download"
        @click="handleProcess"
      >
        {{ $t('processing.downloadProcessing') }}
      </el-button>
      <el-button
        v-if="editRight"
        v-waves
        class="filter-item"
        type="warning"
        icon="el-icon-download"
        @click="handleProcesss"
      >
        {{ $t('processing.downloadProcessings') }}
      </el-button>
    </div>
    <div class="components-container-board">
      <Kanban
        :key="1"
        :delete-enable="true"
        :list="processList"
        :list2="reworkList"
        :group="group"
        class="kanban-normal"
        :header-text="listQuery.processingNumber"
        @save="handleSave"
      />
    </div>
    <div class="select-board">
      <Sticky>
        <Kanban2 :key="3" :delete-enable="false" :list="labelList" :group="group" class="kanban-label" :header-text="$t('produce.processLabel')" @updateData="labelUpdate" />
      </Sticky>
    </div>
    <!-- 新建和更新对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="180px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('processing.processingNumber')" required prop="processingNumber">
          <el-input v-model="temp.processingNumber" />
        </el-form-item>
        <el-form-item :label="$t('order.processRouteVer')">
          <el-input v-model="temp.processingVer" />
        </el-form-item>
        <el-form-item :label="$t('order.mainFlow')">
          <el-input v-model="temp.mainFlow" />
        </el-form-item>
        <el-form-item :label="$t('order.mainFlowSeq')">
          <el-input v-model="temp.mainFlowSeq" />
        </el-form-item>
        <el-form-item :label="$t('order.mainFlowFromOper')">
          <el-input v-model="temp.mainFlowFromOper" />
        </el-form-item>
        <el-form-item :label="$t('order.mainFlowToOper')">
          <el-input v-model="temp.mainFlowToOper" />
        </el-form-item>
        <el-form-item :label="$t('processing.remark')">
          <el-input
            v-model="temp.remark"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 点击下载弹窗 -->
    <el-dialog :title="$t('processing.downloadProcessing')" :visible.sync="dialogForm" class="diag">
      <el-form ref="form" label-width="100px">
        <el-form-item :label="$t('order.orderCode')">
          <el-radio-group
            v-model="checkedCities"
            @change="radiochange"
          >
            <el-row>
              <el-col :span="24">
                <el-radio v-for="(item,index) in orderList" :key="index" :label="item">{{ item }}</el-radio>
              </el-col>
            </el-row>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleDownloadProcess">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 点击下载弹窗 -->
    <el-dialog :title="$t('processing.downloadProcessings')" :visible.sync="dialogForms" class="diag">
      <el-form ref="form" label-width="100px">
        <el-form-item :label="$t('rework.rwkCode')">
          <el-input v-model="rwk.rwkCode" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForms = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleDownloadProcesss">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLineList, getProcessList } from '@/api/equipment'
import { getProcessingList, creatProcessing, updateProcessing, deleteProcessing, getRootList, saveRootList, downloadByOrder, downloadByRwk } from '@/api/processing'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Kanban from '@/components/KanbanTwoLabel'
import Kanban2 from '@/components/KanbanWithScrollBar'
import { getOrderList } from '@/api/order'
import Sticky from '@/components/Sticky'
import i18n from '@/lang'

export default {
  name: 'ProcessingCreate',
  components: { Kanban, Kanban2, Sticky
  },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      rwk: {
        rwkCode: ''
      },
      checkedCities: [],
      checkedC: [],
      orderList: [],
      processLists: [],
      dialogForm: false,
      dialogForms: false,
      editRight: true,
      tableKey: 0,
      list: [],
      group: 'mission',
      sortable: null,
      lineOptions: [],
      processOptions: [],
      processingList: [],
      processList: [],
      reworkList: [],
      labelList: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        lineId: 0,
        typeNo: '',
        lineName: '',
        lineNumber: '',
        processingNumber: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+sequence'
      },
      orderListQuery: {
        page: 1,
        limit: 20,
        state: 0,
        orderCode: '',
        lineNumber: '',
        typeNo: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+due_date'
      },
      orders: {
        orderCodes: ''
      },
      showReviewer: false,
      showRemark: false,
      temp: {
        processingId: 0,
        processingNumber: '',
        lineNumber: '',
        remark: '',
        processingVer: 0,
        mainFlow: '',
        mainFlowSeq: 0,
        mainFlowFromOper: '',
        mainFlowToOper: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        stationNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        stationName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        processingNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        processName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false,
      searchLoading: {
        director: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        director: false
      }
    }
  },
  watch: {
    $route: {
      handler(val) {
        if (this.$route.query.lineNumber !== undefined) {
          this.listQuery.lineNumber = this.$route.query.lineNumber
          this.listQuery.typeNo = this.$route.query.typeNo
          this.getLineOptions()
          this.getProcessOptions()
          this.getList()
          this.listQuery.processingNumber = this.$route.query.processingNumber
          this.getRoots()
        }
      }
    }
  },
  created() {
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    this.listQuery.typeNo = this.$route.query.typeNo
    this.orderListQuery.lineNumber = this.$store.getters.lineNumber
    this.getLineOptions()
    this.getProcessOptions()
    this.getList()
    this.listQuery.processingNumber = this.$route.query.processingNumber
    this.getRoots()
    this.getOrderLists()
  },
  methods: {
    timestepToolTip(index) {
      return index + '%'
    },
    radiochange(e) {
      this.orders.orderCodes = e
    },
    // 下载工艺路径唤起弹窗
    handleProcess() {
      this.dialogForm = true
      this.checkedCities = []
      this.orders.orderCodes = ''
    },
    handleProcesss() {
      this.dialogForms = true
      this.rwk.rwkCode = ''
    },
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 获取线体清单
    getLineOptions() {
      this.listLoading = true
      getLineList(this.listQuery).then(response => {
        this.lineOptions = response.data.lines
        this.listLoading = false
      })
    },
    // 从服务器下载数据
    handleDownloadProcess() {
      this.listLoading = true
      this.$confirm(i18n.t('produce.downloadOrNot'), i18n.t('common.tip'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      }).then(() => {
        downloadByOrder(this.orders).then(response => {
          this.getList()
          this.$message({
            type: 'success',
            message: i18n.t('msg.DOWNLOAD_SUCCESS')
          })
        })
      }).catch(() => {})
      this.listLoading = false
    },
    // 从服务器下载数据
    handleDownloadProcesss() {
      this.listLoading = true
      this.$confirm(i18n.t('produce.downloadOrNot'), i18n.t('common.tip'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      }).then(() => {
        downloadByRwk(this.rwk).then(response => {
          this.getList()
          this.$message({
            type: 'success',
            message: i18n.t('msg.DOWNLOAD_SUCCESS')
          })
        })
      }).catch(() => {})
      this.listLoading = false
    },
    // 获取订单清单
    getOrderLists() {
      this.listLoading = true
      getOrderList(this.orderListQuery).then(response => {
        response.data.orders.forEach(v => {
          this.orderList.push(v.orderCode)
        })
        this.listLoading = false
      })
    },
    // 获取工艺流程选项
    getProcessOptions() {
      this.processOptions = []
      if (this.isEmptyLineId() === false) {
        this.listLoading = true
        getProcessList(this.listQuery).then(response => {
          response.data.processes.forEach(ele => {
            this.processOptions.push({ name: ele.processName, number: ele.processNumber })
          })
          this.processOptions.push({ name: i18n.t('processing.whiteBoard'), number: '-999' })
          this.labelUpdate()
          this.listLoading = false
        })
      }
    },
    labelUpdate() {
      this.labelList = JSON.parse(JSON.stringify(this.processOptions))
    },
    // 判断线体ID是否为空
    isEmptyLineId: function() {
      var ret = (this.listQuery.lineNumber === undefined || this.listQuery.lineNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    // 判断线体ID是否为空
    isEmptyProcessingNumber: function() {
      var ret = (this.listQuery.processingNumber === undefined || this.listQuery.processingNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_PROCESSING_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    handleLineSelect() {
      this.getProcessOptions()
      this.getList()
    },
    // 获取清单
    getList() {
      this.processingList = []
      this.processList = []
      this.reworkList = []
      this.listQuery.processingNumber = ''
      if (this.isEmptyLineId() === false) {
        this.listLoading = true
        getProcessingList(this.listQuery).then(response => {
          this.processingList = response.data.processingDefs
          this.listLoading = false
        })
      }
    },
    // 查看错误信息
    handleCheckOpl(row) {
      const ret = Object.assign({}, row) // copy obj
      this.$router.push({ path: '/project/project_opl', query: { projectNo: ret.projectNo, workName: ret.workName }})
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        processingId: 0,
        processingNumber: '',
        lineNumber: '',
        remark: ''
      }
    },
    // 新建一个工艺路径
    handleCreate() {
      if (this.isEmptyLineId() === false) {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.temp.director = this.$store.getters.name
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    // 创建工艺路径
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lineNumber = this.listQuery.lineNumber
          creatProcessing(this.temp).then(response => {
            this.processingList.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      if (this.isEmptyLineId() === false) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateProcessing(this.temp).then(response => {
            const index = this.list.findIndex(v => v.processingId === this.temp.processingId)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_INFO_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          deleteProcessing(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.DELET_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.processingList.splice(index, 1)
          })
        })
        .catch(err => { console.error(err) })
    },
    // 获取路径
    handleGetRootList(row) {
      if (this.isEmptyLineId() === false) {
        this.temp = Object.assign({}, row) // copy obj
        this.listQuery.processingNumber = this.temp.processingNumber
        this.temp.lineNumber = this.listQuery.lineNumber
        this.getRoots()
      }
    },
    getRoots() {
      if (this.isEmptyLineId() === false && this.isEmptyProcessingNumber() === false) {
        this.processList = []
        this.reworkList = []
        getRootList(this.listQuery).then(response => {
          response.data.processingResults.forEach(ele => {
            this.processOptions.forEach(e => {
              if (e.number === ele.currentProcess) {
                this.processList.push(e)
              }
              if (e.number === ele.reworkProcess) {
                this.reworkList.push(e)
              }
            })
          })
        })
      }
    },
    // 删除数据库信息
    handleSave() {
      if (this.isEmptyLineId() === false && this.isEmptyProcessingNumber() === false) {
        this.$confirm(i18n.t('msg.CONFIRM_SAVE_CHANGE'), i18n.t('common.warn'), {
          confirmButtonText: i18n.t('common.confirm'),
          cancelButtonText: i18n.t('common.cancel'),
          type: 'warning'
        })
          .then(async() => {
            var idx = 0
            const processLen = this.processList.length
            const reworkLen = this.reworkList.length
            var processingResults = []
            this.processList.forEach(ele => {
              processingResults.push({ processingNumber: this.listQuery.processingNumber,
                lineNumber: this.listQuery.lineNumber,
                currentProcess: ele.number,
                nextProcess: processLen > idx + 1 ? this.processList[idx + 1].number : '',
                reworkProcess: reworkLen > idx ? this.reworkList[idx].number : '' })
              idx++
            })
            saveRootList(processingResults).then(response => {
              this.$notify({
                title: this.$i18n.t('common.tip'),
                message: i18n.t('msg.CREAT_SUCCESS'),
                type: 'success',
                duration: 2000
              })
            })
          })
          .catch(err => { console.error(err) })
      }
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.diag{
::v-deep .el-col-24{
    width: 14%!important;
    line-height: 25px!important;
}
::v-deep .el-dialog{
  width: 30vw!important;
}
}
</style>
<style lang="scss">
   .board-column .board-column-content .board-item[data-v-993589a8]{
    width: 92%;
  }
.app-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;
    .filter-containerEx {
    float: left;
    width: 20%;
    }
    .components-container-board {
      float: left;
      width: 60%;
      .kanban-normal{
        float:left;
        width:95%;
        margin-top: 10px;
      }
    }
    .select-board {
      width: 20%;
      height: 10%;
      float: right;
      .kanban-label{
        .board-column-header {
          background: #4A9FF9;
        }
      }
    }
}

.list-complete-item {
  cursor: pointer;
  position: relative;
  font-size: 14px;
  padding: 5px 12px;
  margin-top: 4px;
  border: 1px solid #bfcbd9;
  transition: all 1s;
}

.list-complete-item-handle {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 50px;
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
